package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"ice-tea-mgr/cache"
	"ice-tea-mgr/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.User{

		Title:   title,
		Content: content,
		Author:  author,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Del(c *gin.Context) {
	id, _ := strconv.Atoi(c.PostForm("id"))
	err := models.DB.Where("id = ?", id).Delete(&models.User{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {
	var article []models.User
	redis_list_key := "redis_user"
	userlit, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if userlit == "" {
		models.DB.Debug().Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(userlit), &article)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}
